package panel;

import gui.FrameResultViewer;
import gui.FrameTestErrorGraph;
import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Vector;
import java.awt.GridLayout;
import java.awt.event.InputEvent;
import javax.swing.JScrollPane;
import javax.swing.JList;
import libs.GraphXYValue;
import libs.Utils;

public class PanelReportList extends JPanel {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private JPopupMenu popupMenu;
    private JScrollPane jScrollPane2 = null;
    private JList jList_reports = null;
    private String reportPath; // @jve:decl-index=0:
    public String type;
    public boolean isOnlyPepper = false;
    private String srcPath;
    private static ArrayList<String> mergedErrorList = new ArrayList<String>();  //  @jve:decl-index=0:
    private static ArrayList<String> mergedSpectralBandList = new ArrayList<String>();  //  @jve:decl-index=0:
    private static ArrayList<String> mergedExpNameList = new ArrayList<String>();  //  @jve:decl-index=0:
    private static ArrayList<String> mergedFeatureWeights = new ArrayList<String>();  //  @jve:decl-index=0:
    private static ArrayList<String> mergedRankedFeatureIndex = new ArrayList<String>();  //  @jve:decl-index=0:
    private static ArrayList<String> mergedQuantizationLevel = new ArrayList<String>();  //  @jve:decl-index=0:
    private static int QLevel = 1;
    private static String rankedFeatureWeights = "";  //  @jve:decl-index=0:
    private static String rankedFeatureBands = "";  //  @jve:decl-index=0:
    private static String rankedFeatureIndex = "";  //  @jve:decl-index=0:

    /**
     * This is the default constructor
     */
    public PanelReportList() {
        initialize();
    }
    
    public PanelReportList(String reportPath) {
        super();
        this.reportPath = reportPath;
        initialize();
    }

    private void initialize() {
        GridLayout gridLayout = new GridLayout();
        gridLayout.setRows(1);
        this.setLayout(gridLayout);
        this.setSize(215, 183);
        this.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        this.add(getJScrollPane2(), null);
    }

    protected void println(String msg) {
        System.out.println(msg);
    }

    /**
     * This method initializes jScrollPane2
     *
     * @return javax.swing.JScrollPane
     */
    private JScrollPane getJScrollPane2() {
        if (jScrollPane2 == null) {
            jScrollPane2 = new JScrollPane();
            jScrollPane2.setViewportView(getJList_reports());
        }
        return jScrollPane2;
    }
    /**
     * This method initializes jList_reports
     *
     * @return javax.swing.JList
     */
    public double plotTop;
    public double plotBottom;

    private JList getJList_reports() {
        if (jList_reports == null) {
            jList_reports = new JList();
            loadFileList();
            popupMenuHandler(jList_reports);
            jList_reports.addMouseListener(new java.awt.event.MouseAdapter() {

                public void mouseClicked(java.awt.event.MouseEvent e) {
                    if (e.getClickCount() == 2 && !e.isConsumed()) {
                        e.consume();
                        buildSelfGraph(type, jList_reports);
                    }
                    switch (e.getModifiers()) {
                        case InputEvent.BUTTON3_MASK: {
                            popupMenu.show(e.getComponent(), e.getX(), e.getY());
                            break;
                        }
                    }
                }
            });
        }
        return jList_reports;
    }

    protected void loadFileList() {
        String path = "E:\\DataSet_yeni\\DS\\reports\\LDA\\";
        Vector fileList = getFileList(path);
        jList_reports.setListData(fileList);
    }

    protected void loadFileList(String path) {
        Vector fileList = getFileList(path);
        jList_reports.setListData(fileList);
    }

    private void popupMenuHandler(JList container) {
        // Create some menu items for the popup
        JMenuItem menuFileRename = new JMenuItem("Rename Selected");
        JMenuItem menuFileNew = new JMenuItem("New Folder");
        JMenuItem menuFileDelete = new JMenuItem("Delete Selected");
        JMenuItem menuFileCopy = new JMenuItem("Copy Selected");
        JMenuItem menuFilePaste = new JMenuItem("Paste");
        JMenuItem menuFileEmptyMergePool = new JMenuItem("Empty Merge Pool");
        JMenuItem menuFileMerge = new JMenuItem("Add Selected To Merge Pool");
        JMenuItem menuFilePlotMergedGraph = new JMenuItem("Plot Merged Graph");
        JMenuItem menuFileRefresh = new JMenuItem("Refresh List");
        final JList list = container;
        menuFileRename.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                renameSelected(list);
            }
        });
        menuFileNew.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                newFolder(list);
            }
        });
        menuFileDelete.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                deleteSelected(list);
            }
        });
        menuFileRefresh.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                refreshList();
            }
        });
        menuFileCopy.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                copySelected(list);
            }
        });
        menuFileEmptyMergePool.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                emptyMergePool();
            }
        });
        menuFileMerge.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                MergePool(list);
            }
        });
        menuFilePlotMergedGraph.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                plotMergedGraph();
            }
        });
        menuFilePaste.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                pasteSelected();
            }
        });

        // Create a popup menu
        popupMenu = new JPopupMenu("Menu");
        popupMenu.add(menuFileRename);
        popupMenu.add(menuFileNew);
        popupMenu.add(menuFileDelete);
        popupMenu.add(menuFileCopy);
        popupMenu.add(menuFilePaste);
        popupMenu.add(menuFileEmptyMergePool);
        popupMenu.add(menuFileMerge);
        popupMenu.add(menuFilePlotMergedGraph);
        popupMenu.add(menuFileRefresh);

        container.add(popupMenu);

        // Action and mouse listener support
        enableEvents(AWTEvent.MOUSE_EVENT_MASK);
    }
    private static int expCounter = 0;

    protected void MergePool(JList container) {
        int n = container.getSelectedIndex();
        if (n == -1) {
            return;
        } else {
            String s = container.getSelectedValue().toString();
            Vector<String> v = readClassificationDataFromFile(reportPath + "\\" + s);
            mergedErrorList.add(v.get(3).toString());
            mergedSpectralBandList.add(v.get(4).toString());
            mergedFeatureWeights.add(v.get(5).toString());
            mergedRankedFeatureIndex.add(v.get(6).toString());
            mergedQuantizationLevel.add(v.get(7).toString());
            String exp = v.get(2).toString();
            expCounter++;
            exp = JOptionPane.showInputDialog("Selected Experiment Name", exp);
            mergedExpNameList.add(exp);
        }

    }

    protected void plotEstimatedMergedListGraph(
            FrameResultViewer frm,
            JPanel panXY,
            String[] pepperNames,
            String[] rankedFeatures,
            String[] rankedFeatureWeights,
            String[] rankedBands,
            String[][][] xVal3,
            String[][][] yVal3,
            String[] mergeName,
            String plotTitle,
            String plotXLabel,
            String plotYLabel) {

        float[][][] xVal3f = getFloatValues(xVal3);
        float[][][] yVal3f = getFloatValues(yVal3);
        frm.xVal3 = xVal3f;
        frm.yVal3 = yVal3f;
        frm.pepperNames = pepperNames;
        frm.rankedFeatures = rankedFeatures;
        frm.rankedFeatureWeights = rankedFeatureWeights;
        frm.rankedBands = rankedBands;
        frm.getJSlider_estimationBands().setMinimum(0);
        frm.getJSlider_estimationBands().setMaximum(rankedFeatures[0].split(";").length);
        frm.getJSlider_estimationBands().setValue(0);
        GraphXYValue tempGraph = new GraphXYValue(
                plotTitle,
                plotXLabel,
                plotYLabel,
                xVal3[0],
                yVal3[0],
                mergeName,
                pepperNames,
                1,
                frm.getJSlider_estimationBands());
        panXY.removeAll();
        panXY.add(tempGraph);
        panXY.updateUI();

    }

    private float[][][] getFloatValues(String[][][] p) {
        float[][][] ret = new float[p.length][p[0].length][p[0][0].length];
        for (int i = 0; i < ret.length; i++) {
            for (int j = 0; j < ret[0].length; j++) {
                for (int k = 0; k < ret[0][0].length; k++) {
                    ret[i][j][k] = Float.parseFloat(p[i][j][k]);
                }
            }
        }
        return ret;
    }

    private float[][] getFloatValues2(String[][] p) {
        float[][] ret = new float[p.length][p[0].length];
        for (int i = 0; i < ret.length; i++) {
            for (int j = 0; j < ret[0].length; j++) {
                ret[i][j] = Float.parseFloat(p[i][j]);
            }
        }
        return ret;
    }

    protected void plotMergedListGraph(
            JPanel panXY, String[][] xVal,
            String[][] yVal,
            String[] expName,
            String plotTitle,
            String plotXLabel,
            String plotYLabel,
            JSlider slider,
            int graphType) {

        GraphXYValue tempGraph = new GraphXYValue(plotTitle, plotXLabel, plotYLabel, xVal, yVal, expName, slider, graphType);
        panXY.removeAll();
        panXY.add(tempGraph);
        panXY.updateUI();

    }

    protected void emptyMergePool() {
        mergedErrorList.clear();
        mergedExpNameList.clear();
        mergedSpectralBandList.clear();
    }

    protected void plotMergedGraph() {
        if (!mergedErrorList.isEmpty()) {
            println("mergedList size:" + mergedErrorList.size());
            int expNumber = mergedErrorList.size();
            int dataNumber = mergedErrorList.get(0).split(";").length;
            String[][] xVal = new String[expNumber][dataNumber];
            String[][] yVal = new String[expNumber][dataNumber];
            for (int i = 0; i < expNumber; i++) {
                String[] str = mergedErrorList.get(i).split(";");
                String[] bands = mergedSpectralBandList.get(i).split(";");
                for (int j = 0; j < dataNumber; j++) {
                    xVal[i][j] = bands[j];
                    yVal[i][j] = str[j];
                }
            }
            String[] expName = new String[xVal.length];
            String expNames = "";
            for (int i = 0; i < mergedExpNameList.size(); i++) {
                expNames += mergedExpNameList.get(i).toString() + ";";
                expName[i] = mergedExpNameList.get(i).toString();
            }
            FrameResultViewer frm = new FrameResultViewer(reportPath);
            String plotTitle = JOptionPane.showInputDialog("Write Plot Name", "Plot Title");
            plotMergedListGraph(frm.getJPanel_mergedGraph(), xVal, yVal, expName, plotTitle, "Feature Size", "Classification Error", frm.getJSlider_classification(), -1);


            frm.getJTextArea().append(plotTitle + "\n");
            frm.getJTextArea().append(expNumber + "\n");
            //frm.getJTextArea().append(expNames+"\n");
            for (int i = 0; i < yVal.length; i++) {
                frm.getJTextArea().append(expName[i] + "\n");
                frm.getJTextArea().append(mergedErrorList.get(i) + "\n");
                frm.getJTextArea().append(mergedSpectralBandList.get(i) + "\n");
            }
            frm.getJTextArea().append(mergedFeatureWeights.get(0).toString() + "\n");
            frm.getJTextArea().append(mergedRankedFeatureIndex.get(0).toString() + "\n");
            frm.getJTextArea().append(mergedQuantizationLevel.get(0).toString() + "\n");

            frm.setVisible(true);
        }
    }

    protected void pasteSelected() {
        String fileName = srcPath.substring(srcPath.lastIndexOf("\\"), srcPath.length());
        copyfile(srcPath, reportPath + "\\" + fileName);
        refreshList();
    }

    private static void copyfile(String srFile, String dtFile) {
        try {
            File f1 = new File(srFile);
            File f2 = new File(dtFile);
            InputStream in = new FileInputStream(f1);

            // For Append the file.
            // OutputStream out = new FileOutputStream(f2,true);

            // For Overwrite the file.
            OutputStream out = new FileOutputStream(f2);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            System.out.println("File copied.");
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage() + " in the specified directory.");
            System.exit(0);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    protected void copySelected(JList container) {
        int n = container.getSelectedIndex();
        if (n == -1) {
            return;
        } else {
            String s = container.getSelectedValue().toString();
            srcPath = reportPath + "\\" + s;
        }
    }

    protected void deleteSelected(JList container) {
        int n = container.getSelectedIndex();
        if (n == -1) {
            return;
        } else {
            String s = container.getSelectedValue().toString();
            File file = new File(reportPath + "\\" + s);
            boolean success = file.delete();
            if (success) {
                refreshList();
            }
        }
    }

    protected void newFolder(JList list) {
        String newName = JOptionPane.showInputDialog("Rename Selected Entity",
                "FOLDER");
        boolean success = (new File(this.reportPath + "\\" + newName)).mkdir();
        if (success) {
            refreshList();
        }
    }

    protected void renameSelected(JList container) {
        int n = container.getSelectedIndex();
        if (n == -1) {
            return;
        } else {
            String s = container.getSelectedValue().toString();
            String newName = JOptionPane.showInputDialog(
                    "Rename Selected Entity", s);
            File oldFile = new File(reportPath + "\\" + s);
            File newFile = new File(reportPath + "\\" + newName);
            boolean success = oldFile.renameTo(newFile);
            if (success) {
                refreshList();
            }
        }
    }

    public void refreshList() {
        Vector fileList = getFileList(reportPath);
        jList_reports.setListData(fileList);

    }

    protected void buildSelfGraph(String type, JList obj) {
        String ss = obj.getSelectedValue().toString();
        // println("txt nin yeri"+ss.indexOf(".txt"));
        if (ss.equals("...")) {
            int n = reportPath.lastIndexOf("\\");
            if (n < 0) {
                return;
            }
            reportPath = reportPath.substring(0, n);
            loadFileList(reportPath);
        } else if (ss.lastIndexOf(".merge") > 0) {
            Vector<String> v = null;
            FrameResultViewer frm = new FrameResultViewer(reportPath);
            String fileStr = reportPath + "\\" + ss;
            v = readClassificationDataFromFile(fileStr);

            String plotTitle = v.get(0).toString();
            int expNumber = Integer.parseInt(v.get(1).toString());
            int dataNumber = v.get(3).toString().split(";").length;
            String[][] xVal = new String[expNumber][dataNumber];
            String[][] yVal = new String[expNumber][dataNumber];
            String[] expName = new String[expNumber];
            int lastIndex = 1;
            for (int i = 0; i < expNumber; i++) {
                expName[i] = v.get(i * 3 + 2).toString();
                lastIndex++;
                String[] errs = v.get(i * 3 + 3).toString().split(";");
                lastIndex++;
                String[] bnds = v.get(i * 3 + 4).toString().split(";");
                lastIndex++;
                for (int j = 0; j < errs.length; j++) {
                    xVal[i][j] = bnds[j];
                    yVal[i][j] = errs[j];
                }
            }
            lastIndex++;
            rankedFeatureWeights = v.get(lastIndex).toString();
            lastIndex++;
            rankedFeatureIndex = v.get(lastIndex).toString();
            lastIndex++;
            String[] qs = v.get(lastIndex).toString().split(":");
            QLevel = Integer.parseInt(qs[1]);
            plotMergedListGraph(frm.getJPanel_mergedGraph(), xVal, yVal, expName, plotTitle, "Number of Features", "Classification Error", frm.getJSlider_classification(), -1);
            plotFeatureMapGraph(frm.getJPanel_classificationFeatureMap(), QLevel, rankedFeatureWeights.split(";"), rankedFeatureIndex.split(";"), xVal[0]);
//			plotFeatureMapGraph(frm.getJPanel_featureMap(),QLevel,rankedFeatureWeights.split(";"),rankedFeatureIndex.split(";"),xVal[0]);
            frm.getJSlider_feature().setMinimum(0);
            frm.getJSlider_feature().setMaximum(xVal[0].length);
            frm.setVisible(true);

        } //MLP
        else if (ss.lastIndexOf(".txt") > 0) {
            Vector<String> v = new Vector<String>();
            FrameResultViewer frm = new FrameResultViewer(reportPath);
//			FrameTestErrorGraph frm2=new FrameTestErrorGraph();
//			frm.frm=frm2;
            String fileStr = reportPath + "\\" + ss;

            v = readClassificationDataFromFile(fileStr);
            if (v == null) {
                String dosyaStr = Utils.readPlainTextFromFile(fileStr);
                JTextArea temp = frm.getJTextArea();
                temp.setText(dosyaStr);
                frm.frm = null;
                frm.getJTabbedPane().setSelectedIndex(6);
                frm.setVisible(true);
                return;
            }
            int nPepper = 53;
            if (v.size() > 8) {
                nPepper = Integer.parseInt(v.get(33).toString().split(":")[1]) / 3;
            }
//			float[] testVal=new float[nPepper*3];
//			float[] desiredVal=new float[nPepper*3];
//			String[] peppers=new String[nPepper*3];
//			int k=0;
//			String[] str=null;
//			for (int i = 47; i < 47+nPepper; i++) {
//				str=v.get(i).toString().split(";");
//				testVal[k]=Float.parseFloat(str[3]);
//				testVal[k+nPepper]=Float.parseFloat(str[4]);
//				testVal[k+2*nPepper]=Float.parseFloat(str[5]);
//				desiredVal[k]=Float.parseFloat(str[2]);
//				desiredVal[k+nPepper]=Float.parseFloat(str[2]);
//				desiredVal[k+2*nPepper]=Float.parseFloat(str[2]);
//				peppers[k]=str[1];
//				peppers[k+nPepper]=str[1];
//				peppers[k+2*nPepper]=str[1];
//				k++;
//			}
//			frm2.getJPanel_testError().v=v;
//			frm2.getJPanel_testError().features=v.get(6).toString().split(";");
//			frm2.getJPanel_testError().pepperNames=peppers;
//			String t=v.get(2).toString().split(" ")[1];
//			frm2.getJPanel_testError().type=t.toLowerCase();
//			frm2.getJPanel_testError().setTrainedValues(testVal, desiredVal);

            String plotTitle = v.get(0).toString();
            int expNumber = Integer.parseInt(v.get(1).toString());
            int dataNumber = v.get(3).toString().split(";").length;
            String[][] xVal = new String[expNumber][dataNumber];
            String[][] yVal = new String[expNumber][dataNumber];
            String[] expName = new String[expNumber];
            int lastIndex = 1;
            for (int i = 0; i < expNumber; i++) {
                expName[i] = v.get(i * 3 + 2).toString();
                lastIndex++;
                String[] errs = v.get(i * 3 + 3).toString().split(";");
                lastIndex++;
                String[] bnds = v.get(i * 3 + 4).toString().split(";");
                lastIndex++;
                for (int j = 0; j < errs.length; j++) {
                    xVal[i][j] = bnds[j];
                    yVal[i][j] = errs[j];
                }
            }
            lastIndex++;
            rankedFeatureWeights = v.get(lastIndex).toString();
            lastIndex++;
            rankedFeatureIndex = v.get(lastIndex).toString();
            lastIndex++;
            String[] qs = v.get(lastIndex).toString().split(":");
            QLevel = Integer.parseInt(qs[1]);
            //System.out.println("QLevel:"+QLevel);
            //System.out.println("xval[0][0]:"+xVal[0][0]);
            plotMergedListGraph(frm.getJPanel_classificationGraph(), xVal, yVal, expName, plotTitle, "Number of Features", "Classification Error", frm.getJSlider_classification(), 0);
            plotFeatureMapGraph(frm.getJPanel_classificationFeatureMap(), QLevel, rankedFeatureWeights.split(";"), rankedFeatureIndex.split(";"), xVal[0]);
            plotFeatureMapGraph(frm.getJPanel_featureMap(), QLevel, rankedFeatureWeights.split(";"), rankedFeatureIndex.split(";"), xVal[0]);
            frm.getJSlider_feature().setMinimum(0);
            frm.getJSlider_feature().setMaximum(xVal[0].length);
            frm.getJSlider_classification().setMinimum(0);
            frm.getJSlider_classification().setMaximum(xVal[0].length);
            frm.getJSlider_classification().setValue(0);
            JTextArea temp = frm.getJTextArea();
            if (v.size() > 2) {
                temp.setText("");
                for (int i = 0; i < v.size(); i++) {
                    temp.append(v.get(i) + "\n");
                }
            }
            frm.setVisible(true);
//			int xx=frm.getLocation().x+(frm.getWidth()-frm2.getWidth())/2;
//			frm2.setLocation(xx, frm.getLocation().y+frm.getHeight()/2+30);
//			frm2.setVisible(true);
        } //LDA or SVM
        else if (ss.lastIndexOf(".lda") > 0 || ss.lastIndexOf(".svm") > 0) {
            Vector<String> v = new Vector<String>();
            FrameResultViewer frm = new FrameResultViewer(reportPath);
            String fileStr = reportPath + "\\" + ss;
            v = readClassificationDataFromFile(fileStr);
            int nPepper = 53;
            String plotTitle = v.get(0).toString();
            int expNumber = Integer.parseInt(v.get(1).toString());
            int dataNumber = v.get(3).toString().split(";").length;
            String[][] xVal = new String[expNumber][dataNumber];
            String[][] yVal = new String[expNumber][dataNumber];
            String[] expName = new String[expNumber];
            int lastIndex = 1;
            for (int i = 0; i < expNumber; i++) {
                expName[i] = v.get(i * 3 + 2).toString();
                lastIndex++;
                String[] errs = v.get(i * 3 + 3).toString().split(";");
                lastIndex++;
                String[] bnds = v.get(i * 3 + 4).toString().split(";");
                lastIndex++;
                for (int j = 0; j < errs.length; j++) {
                    yVal[i][j] = errs[j];
                    xVal[i][j] = bnds[j];
                }
            }
            rankedFeatureBands = v.get(lastIndex).toString();
            lastIndex++;
            rankedFeatureWeights = v.get(lastIndex).toString();
            lastIndex++;
            rankedFeatureIndex = v.get(lastIndex).toString();
            lastIndex++;
            String[] qs = v.get(lastIndex).toString().split(":");
            QLevel = Integer.parseInt(qs[1]);
            //System.out.println("QLevel:"+QLevel);
            //System.out.println("xval[0][0]:"+xVal[0][0]);
            plotMergedListGraph(frm.getJPanel_classificationGraph(), xVal, yVal, expName, plotTitle, "Number of Features", "Classification Error", frm.getJSlider_classification(), 0);
            plotFeatureMapGraph(frm.getJPanel_classificationFeatureMap(), QLevel, rankedFeatureWeights.split(";"), rankedFeatureIndex.split(";"), rankedFeatureBands.split(";"));
//			plotFeatureMapGraph(frm.getJPanel_classificationFeatureMap(),QLevel,rankedFeatureWeights.split(";"),rankedFeatureIndex.split(";"),xVal[0]);
//			plotFeatureMapGraph(frm.getJPanel_featureMap(),QLevel,rankedFeatureWeights.split(";"),rankedFeatureIndex.split(";"),xVal[0]);
            plotFeatureMapGraph(frm.getJPanel_featureMap(), QLevel, rankedFeatureWeights.split(";"), rankedFeatureIndex.split(";"), rankedFeatureBands.split(";"));
            frm.getJSlider_feature().setMinimum(0);
            frm.getJSlider_feature().setMaximum(xVal[0].length);
            frm.getJSlider_classification().setMinimum(0);
            frm.getJSlider_classification().setMaximum(xVal[0].length);
            frm.getJSlider_classification().setValue(0);
            JTextArea temp = frm.getJTextArea();
            if (v.size() > 2) {
                temp.setText("");
                for (int i = 0; i < v.size(); i++) {
                    temp.append(v.get(i) + "\n");
                }
            }
            frm.setVisible(true);
        } else if (ss.lastIndexOf(".prediction") > 0) {
            Vector<String> v = new Vector<String>();
            FrameResultViewer frm = new FrameResultViewer(reportPath);
            String fileStr = reportPath + "\\" + ss;
            v = readEstimationDataFromFile(fileStr);

            String plotTitle = "ANN Estimation Results";
            String[] pepperNames = v.get(0).toString().split(";");
            String[] xAxis = new String[pepperNames.length];
            for (int i = 0; i < xAxis.length; i++) {
                xAxis[i] = (i + 1) + "";
            }
            String[] actualValues = v.get(1).toString().split(";");
            int combinationNumber = Integer.parseInt(v.get(2).toString());
            int mergeNumber = 7;
            int dataNumber = pepperNames.length;
            String[][][] xVal3 = new String[combinationNumber][mergeNumber][dataNumber];
            String[][][] yVal3 = new String[combinationNumber][mergeNumber][dataNumber];
            String[] mergeName = new String[mergeNumber];
            mergeName[0] = "Actual";
            mergeName[1] = "Est.1";
            mergeName[2] = "Est.2";
            mergeName[3] = "Est.3";
            mergeName[4] = "Avg.Est";
            mergeName[5] = "MSE";
            mergeName[6] = "Total MSE";
//			int lastIndex=1;
            String[] rankedFeatures = new String[combinationNumber];
            String[] rankedFeatureWeights = new String[combinationNumber];
            String[] rankedBands = new String[combinationNumber];
            String[] est1 = new String[combinationNumber];
            String[] est2 = new String[combinationNumber];
            String[] est3 = new String[combinationNumber];
            int rn = 6;
            int topRow = 3;
            for (int i = 0; i < combinationNumber; i++) {
                rankedFeatures[i] = v.get(i * rn + topRow).toString();
                rankedFeatureWeights[i] = v.get(i * rn + (topRow + 1)).toString();
                rankedBands[i] = v.get(i * rn + (topRow + 2)).toString();
                est1[i] = v.get(i * rn + (topRow + 3)).toString();
                est2[i] = v.get(i * rn + (topRow + 4)).toString();
                est3[i] = v.get(i * rn + (topRow + 5)).toString();
                xVal3[i][0] = xAxis;
                yVal3[i][0] = actualValues;
                xVal3[i][1] = xAxis;
                yVal3[i][1] = est1[i].split(";");
                xVal3[i][2] = xAxis;
                yVal3[i][2] = est2[i].split(";");
                xVal3[i][3] = xAxis;
                yVal3[i][3] = est3[i].split(";");
                xVal3[i][4] = xAxis;
                yVal3[i][4] = getAvgEst(yVal3[i][1], yVal3[i][2], yVal3[i][3]);
                xVal3[i][5] = xAxis;
                yVal3[i][5] = getMSE(yVal3[i][0], yVal3[i][1], yVal3[i][2], yVal3[i][3]);
                xVal3[i][6] = xAxis;
                yVal3[i][6] = getTotalMSE(yVal3[i][0], yVal3[i][1], yVal3[i][2], yVal3[i][3]);
            }
            plotEstimatedMergedListGraph(
                    frm,
                    frm.getJPanel_estimationGraph(),
                    pepperNames,
                    rankedFeatures,
                    rankedFeatureWeights,
                    rankedBands,
                    xVal3,
                    yVal3,
                    mergeName,
                    plotTitle,
                    "Peppers",
                    "%Aflatoxin Level");
            plotFeatureMapGraph(
                    frm.getJPanel_spectralBands(),
                    QLevel,
                    rankedFeatureWeights[0].split(";"),
                    rankedFeatures[0].split(";"),
                    rankedBands[0].split(";"));
            JTextArea temp = frm.getJTextArea();
            if (v.size() > 2) {
                temp.setText("");
                for (int i = 0; i < v.size(); i++) {
                    temp.append(v.get(i) + "\n");
                }
            }
            frm.setVisible(true);

        } else if (ss.lastIndexOf(".combination") > 0 || ss.lastIndexOf(".locs") > 0) {
            Vector<String> v = new Vector<String>();
            FrameResultViewer frm = new FrameResultViewer(reportPath);
            String fileStr = reportPath + "\\" + ss;
            v = readCombinationDataFromFile(fileStr);
            v = Utils.getAdaptiveTresholdValue(v, plotBottom, plotTop);

            String plotTitle = v.get(0);
            String[] classLabels = v.get(1).toString().split(";");
            int numberOfComb = Integer.parseInt(v.get(2).toString());
            if (numberOfComb == 0) {
                numberOfComb = (v.size() - 3) / 2;
            }
            String[] xAxis = new String[numberOfComb];
            for (int i = 0; i < xAxis.length; i++) {
                xAxis[i] = (i + 1) + "";
            }
            String[][] xVal = new String[1][numberOfComb];
            String[][] xBands = new String[1][numberOfComb];
            String[][] yVal = new String[1][numberOfComb];
            int rn = 2;
            int topRow = 3;
            for (int i = 0; i < numberOfComb; i++) {
                xBands[0][i] = v.get(i * rn + (topRow)).toString();
                xVal[0][i] = i + "";
                yVal[0][i] = v.get(i * rn + (topRow + 1)).toString();
            }
            plotCombinationGraph(
                    frm,
                    frm.getJPanel_combinationGraph(),
                    plotTitle,
                    classLabels,
                    xVal,
                    yVal,
                    xBands,
                    "Combinational Features",
                    "Classificiation Error %");
            plotCombinationFeatureMapGraph(
                    frm.getJPanel_combinationBands(),
                    QLevel,
                    classLabels);
            JTextArea temp = frm.getJTextArea();
            if (v.size() > 2) {
                temp.setText("");
                for (int i = 0; i < v.size(); i++) {
                    temp.append(v.get(i) + "\n");
                }
            }
            frm.setVisible(true);

        } else if (ss.lastIndexOf(".single") > 0) {
            Vector<String> v = new Vector<String>();
            FrameResultViewer frm = new FrameResultViewer(reportPath);
            String fileStr = reportPath + "\\" + ss;

            v = readClassificationDataFromFile(fileStr);
            if (isOnlyPepper) {
                int nPepper = Integer.parseInt(v.get(33).toString().split(":")[1]) / 3;
                float[] testVal = new float[nPepper * 3];
                float[] desiredVal = new float[nPepper * 3];
                String[] peppers = new String[nPepper * 3];
                int k = 0;
                String[] str = null;
                for (int i = 47; i < 47 + nPepper; i++) {
                    str = v.get(i).toString().split(";");
                    testVal[k] = Float.parseFloat(str[3]);
                    testVal[k + nPepper] = Float.parseFloat(str[4]);
                    testVal[k + 2 * nPepper] = Float.parseFloat(str[5]);
                    desiredVal[k] = Float.parseFloat(str[2]);
                    desiredVal[k + nPepper] = Float.parseFloat(str[2]);
                    desiredVal[k + 2 * nPepper] = Float.parseFloat(str[2]);
                    peppers[k] = str[1];
                    peppers[k + nPepper] = str[1];
                    peppers[k + 2 * nPepper] = str[1];
                    k++;
                }
                FrameTestErrorGraph frm2 = new FrameTestErrorGraph();
                frm.frm = frm2;
                frm2.getJPanel_testError().v = v;
                frm2.getJPanel_testError().features = v.get(6).toString().split(";");
                frm2.getJPanel_testError().pepperNames = peppers;
                String t = v.get(2).toString().split(" ")[1];
                frm2.getJPanel_testError().type = t.toLowerCase();
                frm2.getJPanel_testError().setTrainedValues(testVal, desiredVal);
                int xx = frm.getLocation().x + (frm.getWidth() - frm2.getWidth()) / 2;
                frm2.setLocation(xx, frm.getLocation().y + frm.getHeight() / 2 + 30);
                frm2.setVisible(true);
            }

            String plotTitle = v.get(0).toString();
            int expNumber = Integer.parseInt(v.get(1).toString());
            int dataNumber = v.get(4).toString().split(";").length;
            String[][] xVal = new String[expNumber][dataNumber];
            String[][] yVal = new String[expNumber][dataNumber];
            String[] expName = new String[expNumber];
            int lastIndex = 1;
            for (int i = 0; i < expNumber; i++) {
                expName[i] = v.get(i * 3 + 2).toString();
                lastIndex++;
                String[] errs = v.get(i * 3 + 3).toString().split(";");
                lastIndex++;
                String[] bnds = v.get(i * 3 + 4).toString().split(";");
                lastIndex++;
                for (int j = 0; j < bnds.length; j++) {
                    xVal[i][j] = bnds[j];
                    yVal[i][j] = errs[0];
                }
            }
            lastIndex++;
            rankedFeatureWeights = v.get(lastIndex).toString();
            lastIndex++;
            rankedFeatureIndex = v.get(lastIndex).toString();
            lastIndex++;
            String[] qs = v.get(lastIndex).toString().split(":");
            QLevel = Integer.parseInt(qs[1]);
            plotMergedListGraph(frm.getJPanel_classificationGraph(), xVal, yVal, expName, plotTitle, "Number of Features", "Classification Error", frm.getJSlider_classification(), 0);
            plotFeatureMapGraph(frm.getJPanel_classificationFeatureMap(), QLevel, rankedFeatureWeights.split(";"), rankedFeatureIndex.split(";"), xVal[0]);
            plotFeatureMapGraph(frm.getJPanel_featureMap(), QLevel, rankedFeatureWeights.split(";"), rankedFeatureIndex.split(";"), xVal[0]);
            frm.getJSlider_feature().setMinimum(0);
            frm.getJSlider_feature().setMaximum(xVal[0].length);
            frm.getJSlider_classification().setMinimum(0);
            frm.getJSlider_classification().setMaximum(xVal[0].length);
            frm.getJSlider_classification().setValue(0);
            JTextArea temp = frm.getJTextArea();
            if (v.size() > 2) {
                temp.setText("");
                for (int i = 0; i < v.size(); i++) {
                    temp.append(v.get(i) + "\n");
                }
            }
            frm.setVisible(true);
        } else if (ss.lastIndexOf(".benchmark") > 0) {
            Vector<String> v = new Vector<String>();
            FrameResultViewer frm = new FrameResultViewer(reportPath);
            String fileStr = reportPath + "\\" + ss;
            v = Utils.readDataFromFile(fileStr);
            frm.loadBenchMarkData(v);
            String dosyaStr = Utils.readPlainTextFromFile(fileStr);
            JTextArea temp = frm.getJTextArea();
            temp.setText(dosyaStr);
            frm.frm = null;
            frm.getJTabbedPane().setSelectedIndex(6);
            frm.setVisible(true);
        } else {
            reportPath += "\\" + ss;
            loadFileList(reportPath);
        }

    }

    private void plotCombinationFeatureMapGraph(PanelFeatureMap panel_combinationBands, int level, String[] classLabels) {
        String[] rnk = new String[classLabels.length];
        String[] rankedIndex = new String[classLabels.length];
        for (int i = 0; i < rankedIndex.length; i++) {
            rnk[i] = "10";
            rankedIndex[i] = i + "";
        }
        panel_combinationBands.setVal(level, rnk, classLabels, rankedIndex);
        panel_combinationBands.setSelectedClassLabels(0);
    }

    private void plotCombinationGraph(FrameResultViewer frm, JPanel panel_combinationGraph, String plotTitle,
            String[] classLabels, String[][] xval,
            String[][] yval, String[][] xBands, String plotXLabel, String plotYLabel) {
        frm.xVal2 = getFloatValues2(xval);
        frm.yVal2 = getFloatValues2(yval);
        frm.classLabels = classLabels;
        frm.xBands = xBands;
        frm.getJSlider_combinationGraph().setMinimum(0);
        frm.getJSlider_combinationGraph().setMaximum(xval[0].length);
        frm.getJSlider_estimationBands().setValue(0);
        String[] expName = {""};
        GraphXYValue tempGraph = new GraphXYValue(
                plotTitle,
                plotXLabel,
                plotYLabel,
                xval,
                yval,
                expName,
                classLabels,
                2,
                frm.getJSlider_combinationGraph());
        panel_combinationGraph.removeAll();
        panel_combinationGraph.add(tempGraph);
        panel_combinationGraph.updateUI();
    }

    private String[] getTotalMSE(String[] act, String[] est1, String[] est2, String[] est3) {
        String[] mse = new String[est1.length];
        double val = 0;
        for (int i = 0; i < mse.length; i++) {
            double n1 = Double.parseDouble(est1[i]) - Double.parseDouble(act[i]);
            n1 *= n1;
            double n2 = Double.parseDouble(est2[i]) - Double.parseDouble(act[i]);
            n2 *= n2;
            double n3 = Double.parseDouble(est3[i]) - Double.parseDouble(act[i]);
            n3 *= n3;
            val += (n1 + n2 + n3) / 3.0;
            mse[i] = val + "";
        }
        return mse;
    }

    private String[] getAvgEst(String[] est1, String[] est2, String[] est3) {
        String[] avg = new String[est1.length];
        for (int i = 0; i < avg.length; i++) {
            double n1 = Double.parseDouble(est1[i]);
            double n2 = Double.parseDouble(est2[i]);
            double n3 = Double.parseDouble(est3[i]);
            double val = (n1 + n2 + n3) / 3.0;
            avg[i] = val + "";
        }
        return avg;
    }

    private String[] getMSE(String[] act, String[] est1, String[] est2, String[] est3) {
        String[] mse = new String[est1.length];
        for (int i = 0; i < mse.length; i++) {
            double n1 = Double.parseDouble(est1[i]) - Double.parseDouble(act[i]);
            n1 *= n1;
            double n2 = Double.parseDouble(est2[i]) - Double.parseDouble(act[i]);
            n2 *= n2;
            double n3 = Double.parseDouble(est3[i]) - Double.parseDouble(act[i]);
            n3 *= n3;
            double val = (n1 + n2 + n3) / 3.0;
            //val=val/100.0;
            //mse[i]=util.formatDouble(val,3)+"";
            mse[i] = val + "";
        }
        return mse;
    }

    private void plotFeatureMapGraph(
            PanelFeatureMap panel_featureMap,
            int qlevel,
            String[] rankedFeatureWeights,
            String[] rankedIndex,
            String[] xval) {
        panel_featureMap.setVal(qlevel, rankedFeatureWeights, xval, rankedIndex);
        panel_featureMap.setSelectedClassLabels(rankedIndex.length);
    }

//	protected void plot(JPanel pan, float[] y, float[] x, String plotTitle,String plotXLabel, String plotYLabel) {
//		GraphXYValue tempGraph = new GraphXYValue(plotTitle, plotXLabel, plotYLabel, x,y);
//		pan.removeAll();
//		pan.add(tempGraph);
//		pan.updateUI();
//	}
    @SuppressWarnings("deprecation")
    private Vector<String> readEstimationDataFromFile(String fileStr) {
        Vector<String> v = new Vector<String>();
        File file = new File(fileStr);
        String pepperNames = "", desiredValues = "";
        int num = 0;
        String rankedFeatures, rankedFeatureWeights, rankedBands;
        String est1, est2, est3;

        try {
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            DataInputStream dis = null;
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);

            dis.readLine();
            pepperNames = dis.readLine();
            dis.readLine();
            desiredValues = dis.readLine();
            dis.readLine();
            num = Integer.parseInt(dis.readLine());

            v.add(pepperNames);
            v.add(desiredValues);
            v.add(num + "");

            for (int i = 0; i < num; i++) {
                dis.readLine();
                rankedFeatures = dis.readLine();
                dis.readLine();
                rankedFeatureWeights = dis.readLine();
                dis.readLine();
                rankedBands = dis.readLine();
                dis.readLine();
                est1 = dis.readLine();
                est2 = dis.readLine();
                est3 = dis.readLine();

                v.add(rankedFeatures);
                v.add(rankedFeatureWeights);
                v.add(rankedBands);
                v.add(est1);
                v.add(est2);
                v.add(est3);
            }
            //geriye kalan tum datayi aliyor
            while (dis.available() != 0) {
                v.add(dis.readLine());
            }
            fis.close();
            bis.close();
            dis.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return v;
    }

    @SuppressWarnings("deprecation")
    private Vector<String> readCombinationDataFromFile(String fileStr) {
        Vector<String> v = new Vector<String>();
        File file = new File(fileStr);
        String plotTitle = "", classLabels = "", selectedFeatures = "", error = "";
        int num = 0;

        try {
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            DataInputStream dis = null;
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);

            plotTitle = dis.readLine();
            classLabels = dis.readLine();
            num = Integer.parseInt(dis.readLine());

            v.add(plotTitle);
            v.add(classLabels);
            v.add(num + "");
            Vector<String> vFt = new Vector<String>();
            Vector<String> vErr = new Vector<String>();
            if (num != 0) {
                for (int i = 0; i < num; i++) {
                    selectedFeatures = dis.readLine();
                    error = dis.readLine();

                    vFt.add(selectedFeatures);
                    vErr.add(error);
                }
            } else {
                while (dis.available() != 0) {
                    selectedFeatures = dis.readLine();
                    error = dis.readLine();

                    vFt.add(selectedFeatures);
                    vErr.add(error);
                }
            }
            //hataya gore buyukten kucuge dogru siraliyoruz.
            double[] err = new double[vErr.size() - 2];
            String[] sF = new String[vFt.size()];
            for (int i = 0; i < err.length; i++) {
                err[i] = Double.parseDouble(vErr.get(i).toString());
                sF[i] = vFt.get(i);
            }
            double temp = 0;
            String s = "";
            for (int i = 0; i < err.length; i++) {
                for (int j = i; j < err.length; j++) {
                    if (err[i] < err[j]) {
                        temp = err[i];
                        err[i] = err[j];
                        err[j] = temp;
                        s = sF[i];
                        sF[i] = sF[j];
                        sF[j] = s;
                    }
                }
            }
            for (int i = 0; i < err.length; i++) {
                v.add(sF[i]);
                v.add(err[i] + "");
            }
            //geriye kalan tum datayi aliyor
            while (dis.available() != 0) {
                v.add(dis.readLine());
            }
            fis.close();
            bis.close();
            dis.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return v;
    }

    @SuppressWarnings("deprecation")
    private Vector<String> readClassificationDataFromFile(String fileStr) {
        Vector<String> v = new Vector<String>();
        File file = new File(fileStr);
        String plotTitle = "";
        int num = 0;
        String expName, errors, bands;

        try {
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            DataInputStream dis = null;
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);

            String ret = "";
            plotTitle = dis.readLine();
            if (plotTitle.indexOf("Window Size") != -1) {
                return null;
            }
            num = Integer.parseInt(dis.readLine());
            v.add(plotTitle);
            v.add(num + "");
            for (int i = 0; i < num; i++) {
                expName = dis.readLine();
                errors = dis.readLine();
                bands = dis.readLine();
                v.add(expName);
                v.add(errors);
                v.add(bands);
            }
            String featureWeights = dis.readLine();
            v.add(featureWeights);
            String featureRankedIndex = dis.readLine();
            v.add(featureRankedIndex);
            String qlevel = dis.readLine();
            v.add(qlevel);
            while (dis.available() != 0) {
                ret = dis.readLine();
                v.add(ret);
            }
            fis.close();
            bis.close();
            dis.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            return null;
        }

        return v;
    }

    protected Vector<String> getFileList(String path) {
        // String reportPath = getDriver() + "\\DataSet_yeni\\DS\\reports\\" +
        // str+
        // "\\";
        if (path.indexOf("\\") < 0) {
            path += "\\";
        }
        reportPath = path;
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();
        Vector<String> ret = new Vector<String>();
        Vector<String> retFile = new Vector<String>();
        Vector<String> retDir = new Vector<String>();
        ret.add("Current Folder is " + path);
        for (int i = 0; i < listOfFiles.length; i++) {
            // ret.add(listOfFiles[i].getName());
            if (listOfFiles[i].isFile()) {
                retFile.add(listOfFiles[i].getName());
            } else if (listOfFiles[i].isDirectory()) {
                retDir.add(listOfFiles[i].getName());
            }
        }
        ret.add("...");
        for (int i = 0; i < retDir.size(); i++) {
            ret.add(retDir.get(i));
        }
        for (int i = 0; i < retFile.size(); i++) {
            ret.add(retFile.get(i));
        }
        return ret;
    }

    public String getReportPath() {
        return reportPath;
    }

    public void setReportPath(String reportPath) {
        this.reportPath = reportPath;
    }
}
